package com.husky.easyexcle.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.fastjson.JSON;
import com.husky.easyexcle.entity.ExcelDateEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author husky
 * @Date 2022/3/14 16:13
 * @Description: easyExcel 工具类
 **/
@Slf4j
public class ExcleUtil {

    /**
     * 读取Excel文件数据
     * @param fileName excel 文件名
     * @param modelPath excel 模型路径
     */
    public static <T> void readExcel(String modelPath,String fileName, Class<T> tclass) {
        //获取根目录
        // ApplicationHome ah = new ApplicationHome(ExcleUtil.class);
        // String excelPath = ah.getSource().getParentFile().toString()+"/excel/";
        ExcelReader excelReader = null;
        AtomicInteger count = new AtomicInteger();
        try {

            EasyExcel.read(getReadPath(modelPath)+fileName, ExcelDateEntity.class, new PageReadListener<T>(
                    dataList -> {
                        for (T demoData : dataList) {

                        }
                        log.info("Excel内容{}", JSON.toJSONString(dataList));
                        count.set(dataList.size());
                        log.info("Excel内容数量：{}",count);
                    }
            )).sheet(0).doRead();
        }catch (Exception e){
            log.error("Excel PageReadListener 读取出错。Exception={}",e);
        }finally {
            if (excelReader != null) {
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
            }
        }
    }

    /**
     * 将数据写入Excel
     * @param fileName 文件名
     * @param sheetName 工作簿名称
     * @param dataList 带写入数据
     * @param headClass 带写入数据对应实体类
     */
    public static <T> void exportExcle(String fileName,String sheetName,List<T> dataList, Class headClass){


        //如果没有文件夹则新建
        File filePath = new File(getWritePath());
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        EasyExcel.write(getWritePath()+fileName, headClass)
                .sheet(sheetName)
                .doWrite(() -> {
                    log.info("待导出数据={}",dataList);
                    return dataList;
                });
    }

    public static void main(String[] args) {
        String poiFilesPath = FileUtils.getPoiFilesPath();
        String cachePath = FileUtils.getCachePath();
        String tempFilePrefix = FileUtils.getTempFilePrefix();
        log.info("临时文件夹 poiFilesPath={},cachePath={},tempFilePrefix={}",poiFilesPath,cachePath,tempFilePrefix);
        List<ExcelDateEntity> list = new CopyOnWriteArrayList<>();
        for(int i=0;i<10000;i++){
            ExcelDateEntity excelDateEntity = new ExcelDateEntity();
            excelDateEntity.setAge(19);
            excelDateEntity.setBirthday(LocalDateTime.now());
            excelDateEntity.setMarriedFlag(true);
            excelDateEntity.setName("林婉儿"+i);
            excelDateEntity.setPartyMemberFlag(1);
            excelDateEntity.setShowFlag("古筝");
            excelDateEntity.setSalary("300.2345");
            excelDateEntity.setStature("173");
            list.add(excelDateEntity);
        }

        ExcleUtil.exportExcle("test.xlsx","我是工作簿",list,ExcelDateEntity.class);
        // ExcleUtil.readExcel("demo","test.xlsx",ExcelDateEntity.class);
    }

    public static <T> List<T> readWebExcelData(MultipartFile file, Class<T> tclass) {
        List<T> resultList = new CopyOnWriteArrayList<>();
        ExcelReader excelReader = null;
        AtomicInteger count = new AtomicInteger();
        try {
            EasyExcel.read(file.getInputStream(), tclass, new PageReadListener<T>(
                    dataList -> {
                        for (T demoData : dataList) {
                            resultList.add(demoData);
                        }
                        log.info("Excel内容{}", JSON.toJSONString(dataList));
                        count.set(dataList.size());
                        log.info("Excel内容数量：{}",count);
                    }

            )).sheet(0).doRead();
            return resultList;
        }catch (Exception e){
            log.error("Excel PageReadListener 读取出错。Exception={}",e);
        }finally {
            if (excelReader != null) {
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
            }
        }
        return resultList;
    }

    /**
     * 获取写出文件目录
     * @return
     */
    private static String getWritePath(){
        //获取根目录
        ApplicationHome ah = new ApplicationHome();

        //excle 导出文件夹
        String excelPath = ah.getDir().getPath()+"/excel/write/";

        //根据年月日创建文件夹
        String timePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).replace("-","/")+"/";
        //如果没有文件夹则新建
        File filePath = new File(excelPath  + timePath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        log.info("excelPath={}",excelPath + timePath);
        return excelPath  + timePath;
    }

    /**
     * 获取 读取文件目录
     * @return
     */
    private static String getReadPath(String modelPath){
        if(!modelPath.endsWith("/")){
            modelPath = modelPath+"/";
        }
        //获取根目录
        ApplicationHome ah = new ApplicationHome();

        //excle 读取文件夹
        String excelPath = ah.getDir().getPath()+"/excel/read/";


        //如果没有文件夹则新建
        File filePath = new File(excelPath  + modelPath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        log.info("excelPath={}",excelPath + modelPath);
        return excelPath  + modelPath;
    }
    /**
     * 获取 模板文件目录
     * @return
     */
    private static String getTemplatePath(String typePath){
        if(!typePath.endsWith("/")){
            typePath = typePath+"/";
        }
        //获取根目录
        ApplicationHome ah = new ApplicationHome();

        //excle 模板文件夹
        String excelPath = ah.getDir().getPath()+"/excel/template/";

        //根据年月日创建文件夹
        // String timePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).replace("-","/")+"/";
        //如果没有文件夹则新建
        File filePath = new File(excelPath + typePath );
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        log.info("excelPath={}",excelPath + typePath );
        return excelPath  + typePath ;
    }
}
